package com.graduation_design.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.entity.AppAddress;
import com.graduation_design.service.AppAddressService;
import com.graduation_design.mapper.AppAddressMapper;
import com.graduation_design.service.AppUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
* @author 从南
* @description 针对表【app_address】的数据库操作Service实现
* @createDate 2024-02-16 18:15:58
*/
@Service
public class AppAddressServiceImpl extends ServiceImpl<AppAddressMapper, AppAddress>
    implements AppAddressService{

    @Resource
    AppUserService appUserService;

    /**
     * 展示默认收货地址
     */
    @Override
    public AppAddress getDefault(long userId) {
        return this.getOne(new QueryWrapper<AppAddress>()
                .eq("is_default", true)
                .eq("user_id", userId)
        );
    }

    /**
     * 查看收货地址时候需要对比一下是不是当前用户的收货地址
     */
    @Override
    public List<AppAddress> listByUserId(long userId) {
        return this.list(new QueryWrapper<AppAddress>()
                .eq("user_id", userId)
                .orderByDesc("created")
        );
    }

    /**
     * 保存收货地址和修改默认
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAndDefault(AppAddress appAddress) {

        Long userId = appUserService.getCurrentUserId();
        if (appAddress.getId() == null) {
            appAddress.setUserId(userId);
            appAddress.setCreated(LocalDateTime.now());
            appAddress.setIsDelete(false);
        } else {

            // 判断下修改的是不是自己的收货地址
            long count = this.count(new QueryWrapper<AppAddress>().eq("user_id", userId).eq("id", appAddress.getId()));
            Assert.isTrue(count > 0, "收货地址不存在");
            appAddress.setUpdated(LocalDateTime.now());
        }

        if (appAddress.getIsDefault()) {
            // 把其他默认的修改为非默认收货地址
            this.update(new UpdateWrapper<AppAddress>()
                    .set("is_default", false)
                    .eq("user_id", userId)
                    .eq("is_default", true)
            );
        }
        this.saveOrUpdate(appAddress);
    }
}




